package com.example.shutdown_v1.controller;

import com.example.shutdown_v1.entity.AlarmRecord;
import com.example.shutdown_v1.entity.DailyInspectionRecord;
import com.example.shutdown_v1.entity.SensorData;
import com.example.shutdown_v1.repository.AlarmRecordRepository;
import com.example.shutdown_v1.repository.DailyInspectionRecordRepository;
import com.example.shutdown_v1.repository.SensorDataRepository;
import com.example.shutdown_v1.repository.SensorRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据统计API
 */
@Slf4j
@RestController
@RequestMapping("/api/statistics")
@RequiredArgsConstructor
public class StatisticsController {

    private final SensorRepository sensorRepository;
    private final SensorDataRepository sensorDataRepository;
    private final AlarmRecordRepository alarmRecordRepository;
    private final DailyInspectionRecordRepository inspectionRecordRepository;
    private final com.example.shutdown_v1.service.DailyInspectionService dailyInspectionService;

    /**
     * 获取系统总览统计
     * GET /api/statistics/overview
     */
    @GetMapping("/overview")
    public ResponseEntity<Map<String, Object>> getOverview() {
        Map<String, Object> response = new HashMap<>();
        
        // 统计传感器总数
        long totalSensors = sensorRepository.count();
        
        // 统计今日数据量
        LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        LocalDateTime now = LocalDateTime.now();
        long todayDataCount = sensorDataRepository.findByReceiveTimeBetween(todayStart, now).size();
        
        // 统计未确认告警
        long unconfirmedAlarms = alarmRecordRepository.findByConfirmedOrderByAlarmTimeDesc(false).size();
        
        // 统计最近7天的告警
        LocalDateTime sevenDaysAgo = now.minusDays(7);
        long recentAlarms = alarmRecordRepository.findAll().stream()
                .filter(a -> a.getAlarmTime().isAfter(sevenDaysAgo))
                .count();
        
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalSensors", totalSensors);
        stats.put("todayDataCount", todayDataCount);
        stats.put("unconfirmedAlarms", unconfirmedAlarms);
        stats.put("recentAlarms", recentAlarms);
        
        response.put("success", true);
        response.put("statistics", stats);
        response.put("timestamp", now);
        
        return ResponseEntity.ok(response);
    }

    /**
     * 获取店铺巡检历史统计
     * GET /api/statistics/inspection-history?shopId={shopId}&days={days}
     */
    @GetMapping("/inspection-history")
    public ResponseEntity<Map<String, Object>> getInspectionHistory(
            @RequestParam Long shopId,
            @RequestParam(defaultValue = "7") int days) {
        
        LocalDateTime startTime = LocalDateTime.now().minusDays(days);
        LocalDateTime endTime = LocalDateTime.now();
        
        List<DailyInspectionRecord> records = inspectionRecordRepository
                .findByShopIdAndInspectionTimeBetween(shopId, startTime, endTime);
        
        // 统计合规率
        long totalInspections = records.size();
        long compliantCount = records.stream().filter(DailyInspectionRecord::getIsCompliant).count();
        double complianceRate = totalInspections > 0 ? (compliantCount * 100.0 / totalInspections) : 0.0;
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("shopId", shopId);
        response.put("days", days);
        response.put("records", records);
        response.put("totalInspections", totalInspections);
        response.put("compliantCount", compliantCount);
        response.put("complianceRate", String.format("%.1f%%", complianceRate));
        
        return ResponseEntity.ok(response);
    }

    /**
     * 获取传感器数据量统计
     * GET /api/statistics/sensor-data?sensorId={sensorId}&start={start}&end={end}
     */
    @GetMapping("/sensor-data")
    public ResponseEntity<Map<String, Object>> getSensorDataStats(
            @RequestParam String sensorId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime start,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime end) {
        
        List<SensorData> dataList = sensorDataRepository.findBySensorIdAndReceiveTimeBetween(sensorId, start, end);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("sensorId", sensorId);
        response.put("startTime", start);
        response.put("endTime", end);
        response.put("dataCount", dataList.size());
        response.put("data", dataList);
        
        return ResponseEntity.ok(response);
    }

    /**
     * 获取告警趋势统计
     * GET /api/statistics/alarm-trend?shopId={shopId}&days={days}
     */
    @GetMapping("/alarm-trend")
    public ResponseEntity<Map<String, Object>> getAlarmTrend(
            @RequestParam(required = false) Long shopId,
            @RequestParam(defaultValue = "7") int days) {
        
        LocalDateTime startTime = LocalDateTime.now().minusDays(days);
        LocalDateTime endTime = LocalDateTime.now();
        
        List<AlarmRecord> alarms;
        if (shopId != null) {
            alarms = alarmRecordRepository.findByShopIdAndAlarmTimeBetween(shopId, startTime, endTime);
        } else {
            alarms = alarmRecordRepository.findAll().stream()
                    .filter(a -> a.getAlarmTime().isAfter(startTime))
                    .toList();
        }
        
        // 按告警类型分组统计
        Map<String, Long> alarmTypeStats = new HashMap<>();
        for (AlarmRecord alarm : alarms) {
            String type = alarm.getAlarmType();
            alarmTypeStats.put(type, alarmTypeStats.getOrDefault(type, 0L) + 1);
        }
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("shopId", shopId);
        response.put("days", days);
        response.put("totalAlarms", alarms.size());
        response.put("alarmTypeStats", alarmTypeStats);
        response.put("alarms", alarms);
        
        return ResponseEntity.ok(response);
    }

    /**
     * 手动触发店铺巡检
     * POST /api/statistics/daily-inspection?shopId={shopId}
     */
    @PostMapping("/daily-inspection")
    public ResponseEntity<Map<String, Object>> triggerDailyInspection(@RequestParam Long shopId) {
        log.info("[手动巡检] API请求触发店铺巡检: shopId={}", shopId);
        
        DailyInspectionRecord record = dailyInspectionService.performInspection(shopId);
        
        Map<String, Object> response = new HashMap<>();
        if (record != null) {
            response.put("success", true);
            response.put("message", "巡检完成");
            response.put("inspection", record);
        } else {
            response.put("success", false);
            response.put("message", "巡检失败，店铺不存在或没有传感器");
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 手动触发全店巡检
     * POST /api/statistics/daily-inspection-all
     */
    @PostMapping("/daily-inspection-all")
    public ResponseEntity<Map<String, Object>> triggerAllDailyInspection() {
        log.info("[手动巡检] API请求触发全店巡检");
        
        List<DailyInspectionRecord> records = dailyInspectionService.performAllInspections();
        
        long compliantCount = records.stream()
                .filter(r -> r.getIsCompliant() != null && r.getIsCompliant())
                .count();
        long totalCount = records.size();
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "全店巡检完成");
        response.put("totalShops", totalCount);
        response.put("compliantShops", compliantCount);
        response.put("nonCompliantShops", totalCount - compliantCount);
        response.put("complianceRate", totalCount > 0 ? String.format("%.1f%%", compliantCount * 100.0 / totalCount) : "0.0%");
        response.put("inspections", records);
        
        return ResponseEntity.ok(response);
    }
}

